/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
package cn.eclass.servlet.admin;

import cn.eclass.bean.api.IAdminBean;
import cn.eclass.entity.AdminEntity;
import cn.eclass.servlet.ActionFace;
import cn.eclass.utils.BeanFactory;
import cn.eclass.utils.Helper;
import com.google.gson.Gson;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;

/**
 *
 * @author fortruththrow new UnsupportedOperationException("Not yet
 * implemented");
 */
public class Admin extends ActionFace {

    IAdminBean bean = BeanFactory.factory.getAdminBean();
    String moduleUrl = this.root + "/admin.jsp";

    public void doCreate() {
        AdminEntity adminEntity = new AdminEntity();
        bean.add(form2Entity(adminEntity));
        this.doIndex();
    }

    public void doUpdate() {
        int id = Integer.valueOf(request.getParameter("id"));
        AdminEntity admin = bean.get(id);
        bean.update(form2Entity(admin));
        this.doIndex();
    }

    public void doDelete() {
        int id = Integer.valueOf(request.getParameter("id"));
        bean.delete(id);
        this.doIndex();
    }

    /**
     * ajax select
     */
    public void doSelect() {
        int id = Integer.valueOf(request.getParameter("id"));
        AdminEntity admin = bean.get(id);
        out.print(new Gson().toJson(admin));
    }

    public void logout() {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    public void login() {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void doIndex() {
        try {
           List<AdminEntity> entities = bean.list();
            
            Field[] fields = AdminEntity.class.getDeclaredFields();
            List<HashMap<String, String>> theFields = Helper.buildField(fields, module);

            request.setAttribute("entities", entities);
            request.setAttribute("fields", theFields);
            request.getRequestDispatcher(tableView).forward(request, response);
        } catch (ServletException ex) {
            Logger.getLogger(Admin.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Admin.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private AdminEntity form2Entity(AdminEntity adminEntity) {
        String username = Helper.toUTF8(request.getParameter("username"));
        String email = Helper.toUTF8(request.getParameter("email"));
        adminEntity.setUsername(username);
        adminEntity.setEmail(email);
        return adminEntity;
    }
}
